package com.enzoism.controller;

import com.enzoism.constants.Constants;
import com.enzoism.model.User;
import com.enzoism.service.UserService;
import com.enzoism.utils.AsyncVo;
import com.enzoism.utils.RequestQueue;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController//该注解替换了原来的@Controller注解
@Api(description = "用户相关",tags={"SwaggerDemoAPi演示"})
@RequestMapping("user")
public class UserController {
 
    @Autowired
    private UserService userService;
 
    @GetMapping("hello")
    public String hello(){
        return  "hello";
    }
 
    @GetMapping("user/{id}")
    @ApiOperation(value="getUserMessage", notes="根据ID获取用户信息!")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
    public User getUserById(@PathVariable String id){
        User user = userService.getUserById(id);
        return user;
    }

    @GetMapping("allUserList")
    public List<User> getAllUserList(){
        List<User> userList = userService.getAllUserList();
        return userList;
    }

    @GetMapping("pageUserList")
    public Map<String,Object> pageUserList(){
        // 使用分页插件,核心代码就这一行，页数、每页行数
        Page<Object> page = PageHelper.startPage(Constants.pageNum, Constants.pageSize);
        // 结果返回
        Map<String,Object> resultMap = new HashMap<>();
        List<User> userList = userService.getAllUserList();
        resultMap.put("userList", userList);
        resultMap.put("total", page.getTotal());
        return resultMap;
    }

    @Autowired
    private RequestQueue queue;

    @GetMapping("/order")
    public DeferredResult<Object> order(String number) throws InterruptedException {
        System.out.println("[ OrderController ] 接到下单请求");
        System.out.println("当前待处理订单数： " + queue.getOrderQueue().size());

        AsyncVo<String, Object> vo = new AsyncVo<>();
        DeferredResult<Object> result = new DeferredResult<>();

        vo.setParams(number);
        vo.setResult(result);

        queue.getOrderQueue().put(vo);
        System.out.println("[ OrderController ] 返回下单结果");
        System.out.println();
        return result;
    }
}